﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Colorful.Caching;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using Volo.Abp.Application.Services;

namespace Colorful.Furniture.MpManagement;

/// <summary>
///  微信公众号JSSDK服务
/// </summary>
public class WechatMpJsSdkAppService : ApplicationService
{
    private readonly IWechatMpExtensions _wechatMpExtensions;
    private readonly WechatMpOptions _wechatMpOptions;
    private readonly WechatApiClient _wechatMpClient;
    private readonly IRedisCache _redisCache;
    private readonly ILogger<WechatMpJsSdkAppService> _logger;
    public WechatMpJsSdkAppService(
        IWechatMpExtensions wechatMpExtensions,
        WechatApiClient wechatMpClient,
        IRedisCache redisCache,
        ILogger<WechatMpJsSdkAppService> logger, 
       IOptions<WechatMpOptions>  wechatMpOptions)
    {
        _wechatMpExtensions = wechatMpExtensions;
        _wechatMpClient = wechatMpClient;
        _redisCache = redisCache;
        _logger = logger;
        _wechatMpOptions = wechatMpOptions.Value;
    }

    /// <summary>
    ///  获取jssdk相关信息
    /// </summary>
    /// <returns></returns>
    public async Task<IDictionary<string, string>> GetAsync(string url)
    {
        var ticket = await _redisCache.GetAsync<string>($"{CachePrefixConst.WechatMpTicket}:{_wechatMpOptions.AppId}");

        if (string.IsNullOrWhiteSpace(ticket))
        {
            var jsApiTicketResponse = await _wechatMpClient.ExecuteCgibinTicketGetTicketAsync(new CgibinTicketGetTicketRequest
            {
                AccessToken =await _wechatMpExtensions.GetAccessTokenAsync()
            });

            _wechatMpExtensions.HandleWxJsonResult(jsApiTicketResponse);

            ticket = jsApiTicketResponse.Ticket;

            try
            {
                await _redisCache.SetAsync($"{CachePrefixConst.WechatMpTicket}:{_wechatMpOptions.AppId}", ticket, jsApiTicketResponse.ExpiresIn);
            }
            catch (Exception e)
            {
                _logger.LogError($"写入公众号票据缓存失败：{e}");
            }
        }

        var data = _wechatMpClient.GenerateParametersForJSSDKConfig(ticket, url);

        return data;
    }
}